// 注入脚本 - 直接在页面上下文中执行
console.log('[Inject] 注入脚本开始执行');

// 立即拦截WebSocket
if (window.WebSocket) {
  console.log('[Inject] 发现WebSocket，开始拦截');
  const originalWebSocket = window.WebSocket;
  
  window.WebSocket = function(url, protocols) {
    console.log('[Inject] *** WebSocket被创建 ***', url, protocols);
    const ws = new originalWebSocket(url, protocols);
    
    // 拦截onmessage
    let originalOnMessage = null;
    Object.defineProperty(ws, 'onmessage', {
      set: function(handler) {
        console.log('[Inject] *** onmessage被设置 ***');
        originalOnMessage = handler;
        
        const wrappedHandler = function(event) {
          console.log('[Inject] *** 收到WebSocket消息 ***');
          const data = typeof event.data === 'string' ? event.data : '[Binary]';
          console.log('[Inject] 数据:', data.substring(0, 100));
          
          // 发送到content script
          window.postMessage({
            type: 'WEBSOCKET_DATA',
            url: url,
            data: event.data,
            timestamp: Date.now()
          }, '*');
          
          if (originalOnMessage) {
            originalOnMessage.call(this, event);
          }
        };
        
        originalWebSocket.prototype.__lookupSetter__('onmessage').call(this, wrappedHandler);
      },
      get: function() {
        return originalOnMessage;
      }
    });
    
    // 拦截send
    const originalSend = ws.send;
    ws.send = function(data) {
      console.log('[Inject] *** WebSocket发送数据 ***');
      const sendData = typeof data === 'string' ? data : '[Binary]';
      console.log('[Inject] 发送:', sendData.substring(0, 100));
      
      // 发送到content script
      window.postMessage({
        type: 'WEBSOCKET_SEND',
        url: url,
        data: data,
        timestamp: Date.now()
      }, '*');
      
      return originalSend.call(this, data);
    };
    
    return ws;
  };
  
  window.WebSocket.prototype = originalWebSocket.prototype;
  window._webSocketIntercepted = true;
  
  console.log('[Inject] WebSocket拦截设置完成');
} else {
  console.log('[Inject] WebSocket不存在');
}